import { defineStore } from 'pinia'
import TokenManager from '../utils/tokenManager'
import { storage } from '../utils/storage'
import { ROLE_CODES } from './role'

export interface Role {
  code: string
  name: string
}

export interface UserInfo {
  userId: string | null
  username: string | null
  avatar: string | null
  email?: string | null
  roles: string[]
  roleObjects: Role[]
  permissions: string[]
  lastActive?: string
}

export interface UserState {
  token: string | null
  userInfo: UserInfo
}

const defaultUserInfo: UserInfo = {
  userId: null,
  username: null,
  avatar: null,
  email: null,
  roles: [] as string[],
  roleObjects: [] as Role[],
  permissions: [] as string[],
  lastActive: undefined
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: TokenManager.getAuthToken(),
    userInfo: storage.get('userInfo', defaultUserInfo) || defaultUserInfo
  }),
  
  getters: {
    getToken: (state) => state.token,
    getUserInfo: (state) => state.userInfo,
    isLoggedIn: (state) => !!state.token,
    
    /**
     * 获取用户角色对象列表
     */
    getRoleObjects: (state) => state.userInfo.roleObjects,
    
    /**
     * 获取角色名称
     * @param roleCode 角色编码
     * @returns 角色名称
     */
    getRoleName: (state) => (roleCode: string): string => {
      const role = state.userInfo.roleObjects.find(r => r.code === roleCode)
      return role?.name || roleCode
    },
    
    /**
     * 检查是否有指定权限
     * @param permission 权限标识
     * @returns boolean
     */
    hasPermission: (state) => (permission: string) => {
      return state.userInfo.permissions.includes('*') || state.userInfo.permissions.includes(permission)
    },
    
    /**
     * 检查是否有指定角色
     * @param role 角色标识
     * @returns boolean
     */
    hasRole: (state) => (role: string) => {
      return state.userInfo.roles.includes(role)
    },
    
    /**
     * 检查是否有指定角色中的任意一个
     * @param roles 角色标识数组
     * @returns boolean
     */
    hasAnyRole: (state) => (roles: string[]) => {
      if (!roles || roles.length === 0) return true
      return state.userInfo.roles.includes(ROLE_CODES.SUPER_ADMIN) || roles.some(r => state.userInfo.roles.includes(r))
    },
    
    /**
     * 检查是否有指定角色中的所有角色
     * @param roles 角色标识数组
     * @returns boolean
     */
    hasAllRoles: (state) => (roles: string[]) => {
      if (!roles || roles.length === 0) return true
      return state.userInfo.roles.includes(ROLE_CODES.SUPER_ADMIN) || roles.every(r => state.userInfo.roles.includes(r))
    },
    
    /**
     * 检查是否是超级管理员
     */
    isSuperAdmin: (state) => {
      return state.userInfo.roles.includes(ROLE_CODES.SUPER_ADMIN)
    },
    
    /**
     * 检查是否是教师
     */
    isTeacher: (state) => {
      return state.userInfo.roles.includes(ROLE_CODES.TEACHER)
    }
  },
  
  actions: {
    /**
     * 设置Token
     * @param token 认证Token
     */
    setToken(token: string) {
      this.token = token
      TokenManager.setAuthToken(token)
      
      // 启动token刷新服务
      TokenManager.getInstance().init()
    },
    
    /**
     * 设置用户信息
     * @param userInfo 用户信息
     */
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
      storage.set('userInfo', userInfo)
    },
    
    /**
     * 添加角色
     * @param role 角色标识
     * @param roleName 角色名称
     */
    addRole(role: string, roleName?: string) {
      if (!this.userInfo.roles.includes(role)) {
        this.userInfo.roles.push(role)
        
        // 同时添加角色对象
        if (roleName) {
          this.userInfo.roleObjects.push({ code: role, name: roleName })
        }
        
        storage.set('userInfo', this.userInfo)
      }
    },
    
    /**
     * 移除角色
     * @param role 角色标识
     */
    removeRole(role: string) {
      const index = this.userInfo.roles.indexOf(role)
      if (index !== -1) {
        this.userInfo.roles.splice(index, 1)
        
        // 同时移除角色对象
        const roleObjIndex = this.userInfo.roleObjects.findIndex(r => r.code === role)
        if (roleObjIndex !== -1) {
          this.userInfo.roleObjects.splice(roleObjIndex, 1)
        }
        
        storage.set('userInfo', this.userInfo)
      }
    },
    
    /**
     * 设置角色
     * @param roles 角色对象数组
     */
    setRoles(roles: Role[]) {
      this.userInfo.roleObjects = roles
      this.userInfo.roles = roles.map(r => r.code)
      storage.set('userInfo', this.userInfo)
    },
    
    /**
     * 登出
     */
    logout() {
      // 停止token刷新服务
      TokenManager.clearAuth()
      
      this.token = null
      this.userInfo = defaultUserInfo
      storage.remove('userInfo')
    }
  }
}) 